<script setup name="Index">
import * as echarts from "echarts"
import { ref } from "vue"
import { getCount, orderList, getDept, getUserTimeOut, getCountByStatus, getCountLast7Days } from "@/api/orderCenter"
import { onMounted } from "vue"
import pieChart from "@/components/echarts/pieChart"
const { proxy } = getCurrentInstance()
const colors = ['#7540ee', '#f765a3', '#49a3e3', '#5470C6', '#91CC75', '#EE6666', '#FAC858', '#73C0DE',
'#3BA272', '#FC8452', '#9A60B4', '#EA7CCC']

const todayWorkOrderStatistics = ref([
  {
    label: "未处理工单",
    id: 0,
    count: 1,
    yesterday: "0%",
    color: "#e2f5ff",
    icon: "<el-icon><Tickets /></el-icon>",
  },
  {
    label: "进行中工单",
    id: 1,
    count: 1,
    yesterday: "0%",
    color: "#f3e8ff",
    icon: "<el-icon><Tickets /></el-icon>",
  },
  {
    label: "已完成工单",
    id: 2,
    count: 1,
    yesterday: "0%",
    color: "#dcfce7",
    icon: "<el-icon><Tickets /></el-icon>",
  },
  {
    label: "超时进行中工单",
    id: 3,
    count: 1,
    yesterday: "0%",
    color: "#ffe2e5",
    icon: "<el-icon><Tickets /></el-icon>",
  },
  {
    label: "超时完成工单",
    id: 4,
    count: 1,
    yesterday: "0%",
    color: "#fff4de",
    icon: "<el-icon><Tickets /></el-icon>",
  },
])

const state = reactive({})
function getList(res) {
  const data = Object.entries(res).map(([name, value], index) => ({
    value,
    name,
    legendname: `rose ${index + 1}`,
    itemStyle: {
      color: colors[index % colors.length] // 防止溢出
    }
  }))
  
  if(data.length === 0) {
    return
  }
  state.dataset = {
    dimensions: ["name", "value"],
    source: data,
  }
}
// 获取工单数量
const getCountData = () => {
  getCountByStatus().then((response) => {
    todayWorkOrderStatistics.value.forEach(item => {
      item.count = 0
    })
    let count = 0
    if(response.data){
      Object.keys(response.data).forEach(key => {
        count += response.data[key]
      })
      let item = response.data
      
      todayWorkOrderStatistics.value[0].count = item.notHandleCount
      todayWorkOrderStatistics.value[0].yesterday = item.notHandleCountPer
      todayWorkOrderStatistics.value[1].count = item.handlingCount
      todayWorkOrderStatistics.value[1].yesterday = item.handlingCountPer
      todayWorkOrderStatistics.value[2].count = item.handledCount
      todayWorkOrderStatistics.value[2].yesterday = item.handledCountPer
      todayWorkOrderStatistics.value[3].count = item.handlingTimeoutCount
      todayWorkOrderStatistics.value[3].yesterday = item.handlingTimeoutCountPer
      todayWorkOrderStatistics.value[4].count = item.handledTimeoutCount
      todayWorkOrderStatistics.value[4].yesterday = item.handledTimeoutCountPer
    }
  })
}
const timeoutOrderList = ref()
const userTimeOutList = ref([])
// 获取超时进行中工单
const getUserTimeOutFn = () => {
  getUserTimeOut().then((response) => {
    userTimeOutList.value = response
  })
}

// 获取超时进行中工单
const getorderList = () => {
  orderList({ status: 2 }).then((response) => {
    timeoutOrderList.value = response.rows
  })
}

const timeOutOrderHandle = () => {
  router.push({
    path: "/order-center/index",
    query: {
      timeoutFlag: 1,
    },
  })
}
//
getCountData()
getorderList()

const callStatsChart = ref(null);
// 来电总数统计：柱状图
const renderCallStatsChart = () => {
  const chart = echarts.init(callStatsChart.value);
  const option = {
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: ['内部门呼', '外部门呼'],
      left: '2%',
      top: 'bottom',
      icon: "circle",
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
    },
    yAxis: {
      type: 'value',
    },
    grid: {
      left: '2%',
      right: '5%',
      bottom: '15%',
      top: '5%',
      containLabel: true,
    },
    series: [
      {
        name: '内部门呼',
        type: 'bar',
        color: '#7540ee', // 柱状图颜色
        data: [120, 132, 101, 134, 90, 230, 210],
        barWidth: 10,
        itemStyle:{
          borderRadius: [20, 20, 0, 0]
        },
      },
      {
        name: '外部门呼',
        type: 'bar',
        color: '#64dfa1', // 柱状图颜色
        data: [220, 182, 191, 234, 290, 330, 310],
        barWidth: 10,
        itemStyle:{
          borderRadius: [20, 20, 0, 0]
        }
      },
    ],
  };
  chart.setOption(option);
};

const departmentCallTrendChart = ref(null);

// 各部门分机接线数量趋势：折线图
const getCountLast7DaysFn = () => {
  getCountLast7Days().then((response) => {
    console.log('11111111', response.data);
    
    renderOrderStatusHeatmapChart(response.data)
  })
}

const renderDepartmentCallTrendChart = (response) => {
  const chart = echarts.init(departmentCallTrendChart.value);
  const option = {
    tooltip: {
      trigger: 'axis',
    },
    grid: {
      left: '2%',
      right: '5%',
      bottom: '15%',
      top: '5%',
      containLabel: true,
    },
    legend: {
      left: '2%',
      top: 'bottom',
      data: ['客房服务部', '礼宾部', '大客户部'],
      icon: "rect",
      itemWidth: 20, // 长方形宽度
      itemHeight: 10, // 长方形高度
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: '客房服务部',
        type: 'line',
        symbolSize: 8,
        color: '#60afe7',
        symbol: 'circle',
        data: [50, 70, 60, 90, 120, 150, 100],
      },
      {
        name: '礼宾部',
        type: 'line',
        symbolSize: 8,
        color: '#895bf0',
        symbol: 'circle',
        data: [30, 40, 50, 60, 80, 100, 120],
      },
      {
        name: '大客户部',
        type: 'line',
        symbolSize: 8,
        color: '#fba4c9',
        symbol: 'circle',
        data: [20, 30, 40, 50, 60, 70, 80],
      },
    ],
  };
  chart.setOption(option);
};

const orderStatusHeatmapChart = ref(null);
const status = ['未处理', '进行中', '已完成', '超时进行中', '超时完成'];

// 工单状态占比统计：热力图
const renderOrderStatusHeatmapChart = (workOrderData) => {
  let heatmapData = []
  const statusLabels = ['notHandleCount', 'handlingCount', 'handledCount', 'handlingTimeoutCount', 'handledTimeoutCount']
  const xAxisData = []
  let pieces = [
    {min: 80, max: 100, label: status[4], color: '#381e75'},
    {min: 60, max: 80, label: status[3], color: '#6132cb'},
    {min: 40, max: 60, label: status[2], color: '#7540ee'},
    {min: 20, max: 40, label: status[1], color: '#a07cf3'},
    {min: 0, max: 20, label: status[0], color: '#d6c7f9'},
  ]
  // 工单状态占比统计：热力图
  workOrderData.forEach((dayData,i) => {
    xAxisData.push(dayData.date)
    const total = dayData.total || 0
    let dayDataArr = []
    statusLabels.forEach((key, y) => {
      const count = dayData[key] || 0
      const percent = total > 0 ? Math.round((count / total) * 100) : 0
      dayDataArr.push([percent, status[y], dayData[key+'Per']])
    })
    const sortedIndices = [...dayDataArr.keys()].sort((a, b) => dayDataArr[a] - dayDataArr[b]);
    const getYAxisIndex = (val) => {
      if (val < 20) return 0;
      if (val < 40) return 1;
      if (val < 60) return 2;
      if (val < 80) return 3;
      return 4;
    };
    heatmapData = [...heatmapData, ...sortedIndices.map((index) => {
      
      const val = dayDataArr[index][0];
      const y = getYAxisIndex(val);
      if( val === 0) return [-1, 0, 0]; // 如果值为0则不添加到热力图数据中
      // 根据 val 值判断当前属于哪个区间，设置对应颜色
      // 根据 pieces 数组匹配 dayDataArr[index][1] === piecesz中的label，匹配上则取对应 color
      let color = '';
      const matchedPiece = pieces.find(piece => piece.label === dayDataArr[index][1]);
      if (matchedPiece) {
        color = matchedPiece.color;
      } else {
        color = '#d6c7f9';
      }
      return {
        value:[i, y, val, {
        name: dayDataArr[index][1],
        value: dayDataArr[index][2]
      }],
        itemStyle: {
          color: color
        }
      };
    })]
  })
  
  const chart = echarts.init(orderStatusHeatmapChart.value);
    const option = {
      tooltip: {
        position: 'top',
        formatter: params => {
          return `${params.value[3].name}工单: ${params.value[3].value} `
        }
      },
      grid: {
        left: '2%',
        right: '2%',
        bottom: '15%',
        top: '5%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        data: xAxisData,
        splitLine: { show: false },
      },
      yAxis: {
        type: 'category',
        data: ['20%', '40%', '60%', '80%', '100%'],
        splitLine: { show: false },
      },
      legend: {
        type: "scroll",
      },
      visualMap: {
        type: 'piecewise',
        min: 0,
        max: 100,
        calculable: true,
        orient: 'horizontal',
        left: 'center',
        top: 'bottom',
        itemWidth: 10,
        itemHeight: 10,
        pieces,
        textStyle: {
          width: 10,
          overflow: 'truncate'
        }
      },
      series: [
        {
          type: 'heatmap',
          data: heatmapData,
          label: {
            show: false,
            color: '#000',
            fontSize: 12,
          },
          itemStyle: {
            borderWidth: 1,
            borderColor: '#fff',
          },
        },
      ],
    };
    chart.setOption(option);
};

onMounted(() => {
  renderCallStatsChart();
  getCountLast7DaysFn();
  renderDepartmentCallTrendChart();
  getDeptFn()
  getUserTimeOutFn()
})

const getDeptFn = () => {
  getDept().then((response) => {
    getList(response)
  })
}

</script>

<template>
  <div class="app-container home">
    <div class="card-one">
      <div style="flex: 1" class="home-title font-bold text-yellow-200">总览</div>
      <el-select v-model="value" placeholder="最近7天数据" style="width: 180px">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-select v-model="value" placeholder="分店" style="width: 120px">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </div>
    <div class="card card-two">
      <div class="card-title">本日工单统计</div>
      <ul>
        <li
          v-for="(item, index) in todayWorkOrderStatistics"
          :key="index"
          class="liStyle"
          :style="{ backgroundColor: item.color }"
        >
          <div
            class="today-work__icon"
            v-if="item.label == '未处理工单'"
            style="display: flex; justify-content: center; align-items: center"
          >
            <img src="@/assets/images/wcl.png" alt="2" style="width: 15px; height: 15px" />
          </div>
          <div
            class="today-work__icon"
            v-if="item.label == '进行中工单'"
            style="
              display: flex;
              justify-content: center;
              align-items: center;
              background-color: #bf83ff;
            "
          >
            <img src="@/assets/images/jxz.png" alt="2" style="width: 15px; height: 15px" />
          </div>
          <div
            class="today-work__icon"
            v-if="item.label == '已完成工单'"
            style="
              display: flex;
              justify-content: center;
              align-items: center;
              background-color: #3cd856;
            "
          >
            <img src="@/assets/images/tab.png" alt="2" style="width: 15px; height: 15px" />
          </div>
          <div
            class="today-work__icon"
            v-if="item.label == '超时进行中工单'"
            style="
              display: flex;
              justify-content: center;
              align-items: center;
              background-color: #fa5a7d;
            "
          >
            <img src="@/assets/images/wcl.png" alt="2" style="width: 15px; height: 15px" />
          </div>
          <div
            class="today-work__icon"
            v-if="item.label == '超时完成工单'"
            style="
              display: flex;
              justify-content: center;
              align-items: center;
              background-color: #ff947a;
            "
          >
            <img src="@/assets/images/complete.png" alt="2" style="width: 15px; height: 15px" />
          </div>
          <div class="today-work__count" style="padding: 3px 0">{{ item.count }}</div>
          <div class="today-work__status-label">{{ item.label }}</div>
          <div class="today-work__yesterday">{{ item.yesterday }}</div>
        </li>
      </ul>
    </div>
    <div class="card card-three">
      <div class="card-title">工单状态占比统计</div>
      <div class="card-body"  ref="orderStatusHeatmapChart"></div>
    </div>
    <div class="card card-four">
      <div class="card-title">来电总数统计</div>
      <div class="card-body" ref="callStatsChart"></div>
    </div>
    <div class="card card-five">
      <div class="card-title">各部门分机接线数量趋势</div>
      <div class="card-body" ref="departmentCallTrendChart"></div>
    </div>
    <div class="card card-six">
      <div class="card-title">各部门工单数量统计</div>
      <div class="card-body">
        <pieChart
          :dataset="state.dataset"
          :loading="state.loading"
          :radius="[25, 100]"
          :color="colors"
          :legendShow="true"
          fixColor
        />
      </div>
      <div class="card-title">超时工单最多员工</div>
      <div class="card-body">
        <ul class="ulScroll">
          <li v-for="(item, index) in userTimeOutList" :key="index" class="flex" style="line-height: 25px;">
            <div class="w-[25px]" style="font-size: 14px; color: #8a878e">{{ index + 1 }}</div>
            <div class="w-[30px]" style="margin-right: 10px;margin-top: 6px;">
              <img src="@/assets/images/profile.jpg" alt="" style="vertical-align: middle;border-radius: 50%;">
            </div>
            <div class="flex-1" style="font-size: 14px; line-height: 1.6">
              <div>{{ item.userName }}</div>
              <div class="textStyle">{{ item.totalCount }}个工单 -  {{ item.timeoutRate === 0 ? '0%' : (item.timeoutRate).toFixed(2) + '%' }}超时</div>
            </div>
            <div class="w-[25px]" @click="timeOutOrderHandle">
              <el-icon style="color: #e64343; font-size: 25px; vertical-align: -webkit-baseline-middle">
                <CaretTop />
              </el-icon>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <div class="card card-seven">
      <div class="card-title">超时进行中工单</div>
      <div class="card-body">
        <ul class="ulScroll">
          <li v-for="(item, index) in timeoutOrderList" :key="index" class="flex">
            <div class="flex-1" style="display: flex">
              <div
                style="font-size: 14px; color: #8a878e; padding-right: 15px; box-sizing: border-box"
              >
                # {{ item.orderId }}
              </div>
              <div style="font-size: 14px">{{ item.orderTitle }}</div>
            </div>
            <div class="w-[25px]" @click="timeOutOrderHandle">
              <el-icon style="color: #7540ee; font-size: 20px;cursor: pointer;"><Right /></el-icon>
            </div>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.home {
  height: 100%;
  display: grid;
  row-gap: 10px;
  column-gap: 10px;
  grid-template-areas:
    "a a a"
    "b b f"
    "c d f"
    "e e g";
  grid-template-rows: 63px 21fr 31fr 31fr;
  grid-template-columns: 38fr 43fr 48fr;
  .card-one {
    border-radius: 6px;
  }
  .card {
    display: flex;
    flex-direction: column;

    &-one {
      grid-area: a;
      background: #fff;

      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 12px;
      padding: 0 20px;
      // font-weight: 700;
      font-size: 20;
      // background-color: #fff;
      margin-bottom: 10px;
    }
    &-two {
      grid-area: b;
      // background: #000;
    }
    &-three {
      grid-area: c;
      background: #000;
    }
    &-four {
      grid-area: d;
      background: #000;
    }
    &-five {
      grid-area: e;
      background: #000;
    }
    &-six {
      grid-area: f;
      background: #000;
    }
    &-seven {
      grid-area: g;
      background: #000;
    }
  }

  .home-title {
    font-size: 20px;
    font-weight: 700;
    color: #1d1b20;
  }

  .card {
    padding: 15px 25px;
    background: #fff;
    border-radius: 12px;
  }
  .card-body {
    flex: 1;
    .ulScroll {
      height: 200px;
      overflow: scroll;
      user-select: none;
      margin-top: 10px;
      margin-right: -15px;
      &::-webkit-scrollbar {
        width: 3px;
        height: 0px;
        margin-top: 5px;
        background: #f7f7f9;
      }
      &::-webkit-scrollbar-track-piece {
        /*滚动条背景颜色*/
        background: #f7f7f9;
      }
      &::-webkit-scrollbar-thumb {
        /* 滑块 */
        border-radius: 5px;
        height: 50px;
        width: 20px;
        // box-shadow: inset 0 0 0px #606987;
        background: #d4d9e2;
      }
    }
  }
  .card-title {
    margin-bottom: 16px;
    font-size: 16px;
    font-weight: 700;
    color: #05004e;
  }

  .card-two {
    display: flex;
    flex-direction: column;

    ul {
      flex: 1;
      display: flex;
      align-items: stretch;
      justify-content: space-between;
      gap: 24px;
      padding: 0;
      margin: 0;
    }
    li {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      padding: 15px;
      border-radius: 10px;
      font-size: 14px;
    }
    .today-work {
      &__icon {
        width: 30px;
        height: 30px;
        background-color: #49a3e3;
        border-radius: 30px;
      }
      &__count {
        font-size: 22px;
        font-weight: 700;
        color: #151d48;
      }
      &__status-label {
        font-size: 14px;
        color: #425166;
      }

      &__yesterday {
        font-size: 12px;
        color: #4079ed;
      }
    }
  }
}

.textStyle {
  font-size: 12px;
  color: #8a878e;
}
</style>
